import {getStore, removeStore, setStore} from '@/util/store'
import {removeToken, setToken} from '@/util/auth'
import {generateToken} from '@/api/user'

const user = {
    state: {
        userInfo: getStore({name: 'userInfo'}) || [],
        token: getStore({name: 'token'}) || '',
    },
    actions: {
        GenerateToken({commit}, user) {
            return new Promise((resolve, reject) => {
                generateToken(user).then(res => {
                    const data = res.data;
                    commit('SET_USER', user);
                    commit('SET_TOKEN', data);
                    resolve();
                }).catch(error => {
                    reject(error);
                })
            })
        },
        ClearToken({commit}) {
            commit('REMOVE_TOKEN');
            commit('REMOVE_USER');
        }
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            setToken(token);
            state.token = token;
            setStore({name: 'token', content: state.token, type: 'session'})
        },
        SET_USER: (state, userInfo) => {
            state.userInfo = userInfo;
            setStore({name: 'userInfo', content: state.userInfo})
        },
        REMOVE_TOKEN: (state) => {
            removeToken();
            state.token = '';
            removeStore({name: 'token', type: 'session'});
        },
        REMOVE_USER: (state) => {
            state.userInfo = '';
            removeStore({name: 'userInfo'});
        }
    }
};

export default user
